package com.mwx.loseweight.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mwx.loseweight.common.result.Result;
import com.mwx.loseweight.pojo.dto.UserPageDTO;
import com.mwx.loseweight.pojo.entity.User;
import com.mwx.loseweight.pojo.vo.UserLoginVO;
import com.mwx.loseweight.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理API")
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result addUser(@RequestBody User userDTO) {
        //查询用户
        User user = userService.findByUserName(userDTO.getUsername());
        if (user == null) {
            //没有占用
            //注册
            userService.save(userDTO);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> userLogin(@RequestBody User userDTO, HttpServletResponse response) {
        //调用MD5工具类进行加密
        String Md5Password= DigestUtils.md5Hex(userDTO.getPassword());
        //根据用户名查询用户
        User loginUser = userService.findByUserName(userDTO.getUsername());
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户不存在");
        }
        if (Md5Password.equals(loginUser.getPassword())) {
            UserLoginVO userLoginVO = new UserLoginVO();
            BeanUtils.copyProperties(loginUser, userLoginVO);
            setUserInfoToCookie(userLoginVO, response);
            return Result.success(userLoginVO);
        }
        return Result.error("密码错误");
    }

    @SneakyThrows
    private void setUserInfoToCookie(UserLoginVO userLoginVO, HttpServletResponse response) {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(userLoginVO);
        String encodedUserInfo = URLEncoder.encode(json, StandardCharsets.UTF_8);
        Cookie cookie = new Cookie("userInfo", encodedUserInfo);
        cookie.setPath("/"); // 设置Cookie的有效路径
        response.addCookie(cookie);
    }

    // 修改后的退出登录方法
    @PostMapping("/logout")
    @Operation(summary = "用户退出登录")
    public Result userLogout(HttpServletResponse response) {
        UserLoginVO userLoginVO = new UserLoginVO();
        setUserInfoToCookie(userLoginVO, response);
        return Result.success();
    }

    @PostMapping("/delete")
    @Operation(summary = "删除用户")
    public Result deleteUser(@RequestBody User user) {
        userService.delete(user);
        return Result.success();
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户信息")
    public Result updateUser(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @PostMapping("/updatePassword")
    @Operation(summary = "更新用户信息")
    public Result updatePassword(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @PostMapping("/get")
    @Operation(summary = "获取用户详情")
    public Result<User> getUser(@RequestBody User user) {
        User savedUser = userService.get(user);
        return Result.success(savedUser);
    }

    @PostMapping("/list")
    @Operation(summary = "获取用户列表")
    public Result<Page<User>> getUserList(@RequestBody UserPageDTO userPageDTO) {
        Page<User> pageResult = userService.list(userPageDTO);
        return Result.success(pageResult);
    }

}
